import Cookies from 'js-cookie'
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // 进度条
import 'nprogress/nprogress.css' 
import { getToken,getRoles } from '@/utils/auth' // 从Cookie中拿token和role
import getPageTitle from '@/utils/get-page-title'
NProgress.configure({ showSpinner: false }) 
const whiteList = ['/login',"/dashboard"] // 没有token也放行的路径
router.beforeEach(async(to, from, next) => {
  //进度条和获取标题
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  //根据token判断是否已经登录
  const hasToken = getToken();
  console.log(hasToken);
  //已登录
  if (hasToken) {
    if (to.path === '/login') {
      // 如果还去登录页面，直接跳转首页
      console.log("登录");
      next({ path: '/' })
      NProgress.done(); 
    } else {
      //不是去登录
        next();
        console.log(getRoles()); 
        const roles  = getRoles();//获取角色
        const accessRoutes = await store.dispatch('permission/generateRoutes', [roles]);
        router.addRoutes(accessRoutes);
      
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      // next(`/login?redirect=${to.path}`);
      next();
      NProgress.done();
    }
  }
})

router.afterEach(() => {
  // 完成页面进度条
  NProgress.done()
})


